<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | fastadmin: https://www.fastadmin.net/
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 手机短信接口
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\Sms as SmsModel;
use app\member\model\Member;
use think\Exception;
use think\facade\Hook;
use think\facade\Validate;

/**
 * @title 手机短信接口
 * @controller api\controller\Sms
 * @group base
 */
class Sms extends Api
{

//    /**
//     * @title 发送验证码
//     * @desc 最基础的接口注释写法
//     * @url 192.168.101.21/api/Sms/send
//     * @method GET
//     * @tag 手机 验证码
//     * @param name:mobile type:string require:1 desc:手机号
//     * @param name:event type:string require:1 desc:事件名称
//     * @return name:data type:array ref:definitions\dictionary
//     */
//    public function send()
//    {
//        $mobile = $this->request->request("mobile");
//        $event  = $this->request->request("event");
//        $event  = $event ? $event : 'register';
//
//        if (!$mobile || !Validate::isMobile($mobile)) {
//            $this->error('手机号不正确');
//        }
//        $last = Smslib::get($mobile, $event);
//        if ($last && time() - $last['create_time'] < 60) {
//            $this->error('发送频繁');
//        }
//        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('create_time', '-1 hours')->count();
//        if ($ipSendTotal >= 5) {
//            $this->error('发送频繁');
//        }
//        if ($event) {
//            $userinfo = Member::getByMobile($mobile);
//            if ($event == 'register' && $userinfo) {
//                $this->error('已被注册');
//            } elseif (in_array($event, ['changemobile']) && $userinfo) {
//                $this->error('已被占用');
//            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//                $this->error('未注册');
//            }
//        }
//        if (!Hook::get('sms_send')) {
//            $this->error('请在后台插件管理安装短信验证插件');
//        }
//        $ret = Smslib::send($mobile, null, $event);
//        if ($ret) {
//            $this->success('发送成功');
//        } else {
//            $this->error('发送失败');
//        }
//
//    }

//    /**
//     * @title 检测验证码
//     * @desc 最基础的接口注释写法
//     * @url /api/Sms/check
//     * @method GET
//     * @tag 手机 验证码
//     * @param name:mobile type:string require:1 desc:手机号
//     * @param name:event type:string require:1 desc:事件名称
//     * @param name:code type:string require:1 desc:验证码
//     * @return name:data type:array ref:definitions\dictionary
//     */
//    public function check(){
//
//        $data = input("get.");
//        try {
//            $result = Smslib::check($data['mobile'],$data['code'],$data['event']);
//            if($result){
//                $this->success("验证通过");
//            }else{
//                $this->error("验证失败");
//            }
//        }catch (Exception $e){
//            $this->error("验证异常");
//        }
//    }

    /**
     * @title 发送短信验证码
     * @url /api/Sms/sendCode
     * @method GET
     * @param  name:mobile type:string require:1 desc: 电话号码
     * @param name:event type:string require:1 desc:事件注册：register登录：login,修改密码：modifyPassword修改手机：modifyMobile
     * @return name:data type:array ref:definitions\dictionary
     */
    public function sendCode(){
        $data = input("get.");
        if(isset($data['mobile'])){
            if(!isset($data['event'])){
                $this->error("事件不能为空");
            }
            $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('create_time', '-5 min')->count();
            if ($ipSendTotal >= 3) {
                $this->error('发送频繁');
            }
            //查询电话
//            $userinfo = Member::getByMobile($data['mobile']);
//            if ($data['event'] == 'register' && $userinfo) {
//                $this->error('已被注册');
//            } elseif (in_array($data['event'], ['changemobile']) && $userinfo) {
//                $this->error('已被占用');
//            } elseif (in_array($data['event'], ['changepwd', 'resetpwd']) && !$userinfo) {
//                $this->error('未注册');
//            }
            $code = rand(100000,999999);
            $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
            $smsConf = array (
                'key' => '606591cf3b2483f1757974c411f729d7', //您申请的APPKEY
                'mobile' => $data['mobile'], //接受短信的用户手机号码
                'tpl_id' => '228764', //您申请的短信模板ID，根据实际情况修改
                'tpl_value' => '#code#='.$code.'&#m#=1'
            );
            //保存数据库
            $time   = time();
            $sms = SmsModel::create(['event' => $data['event'], 'mobile' => $data['mobile'], 'code' => $code, 'create_time' => $time]);
            if(!$sms){
                $this->error("验证码错误");
                exit();
            }
            $content = $this->juhecurl($sendUrl, $smsConf, 1);
            if($content){
                $this->success("发送成功");
            }else{
                $this->error("发送失败");
            }
        }else{
            $this->error("电话号码不能为空");
        }
        exit();
    }

    /**
     * curl
     * @param $url
     * @param false $params
     * @param int $ispost
     * @return bool|string
     */
   private function juhecurl($url, $params = false, $ispost = 0) {
        $httpInfo = array ();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

}
